/**
 * @file 窗口工具
 * @description 提供窗口操作和事件处理的通用工具方法
 * @author 黄敏
 * @version 1.0.0
 * @since 2025-08-12
 */

import type { BrowserWindowConstructorOptions, WebContents } from 'electron'
import type { CreateState } from 'global-state'
import type { WindowState } from '~types/global-state'
import { BrowserManager } from '#/browser'
import { getWindowBackgroundColor, ICON_PATH, isDarkMode } from '#/utils/paths'
import { BaseWindow } from 'electron'
import debounce from 'lodash/debounce'
import { isBlankUrl, isLocalFileUrl } from '~shared/utils/urlUtils'

/**
 * 为 WebContents 设置窗口打开处理器
 * @param webContents - WebContents 实例
 * @param sourceId - 源标签页ID
 * @param onCreateTab - 创建标签页的回调函数
 * @description 处理页面中的窗口打开请求，根据不同的打开方式创建新窗口或新标签页
 * @example
 * ```ts
 * setupWindowOpenHandler(webContents, tabId, (tabParams) => {
 *   console.log('创建新标签页:', tabParams)
 * })
 * ```
 */
export function setupWindowOpenHandler(
  webContents: WebContents,
  sourceId: number,
  onCreateTab: (tabParams: F2.tab.Create) => void
): void {
  webContents.setWindowOpenHandler(details => {
    const { url, frameName } = details

    const width = Number(/width=(\d+)/.exec(details.features)?.[1])
    const height = Number(/height=(\d+)/.exec(details.features)?.[1])

    if (details.disposition === 'foreground-tab' || !width || !height) {
      // 过滤掉空白页和本地文件
      if (!isBlankUrl(url) && !isLocalFileUrl(url)) {
        if (details.disposition === 'new-window') {
          // 在新窗口中打开
          BrowserManager.getInstance().createNewWindow(url)
        } else {
          // 在新标签页中打开
          onCreateTab({
            url,
            title: frameName || url,
            autoFocus: details.disposition === 'foreground-tab',
            source: {
              type: 'tab',
              id: sourceId,
              originalUrl: url
            }
          })
        }
      }
      return { action: 'deny' }
    } else {
      return {
        action: 'allow',
        overrideBrowserWindowOptions: {
          titleBarStyle: 'hidden',
          titleBarOverlay: true,
          width,
          height
        }
      }
    }
  })
}

/**
 * 创建基础窗口
 * @param store - 窗口状态存储实例
 * @param opts - 额外的窗口配置选项
 * @returns BaseWindow - 创建的窗口实例
 * */
export function createBaseWindow(
  store: CreateState<WindowState>,
  opts?: Partial<BrowserWindowConstructorOptions>
) {
  // 获取系统标题栏样式配置
  const savedWindowState = store.state

  // 构建Electron窗口配置选项
  const windowOptions: BrowserWindowConstructorOptions = {
    icon: ICON_PATH,
    darkTheme: isDarkMode(),
    backgroundColor: getWindowBackgroundColor(),
    width: savedWindowState.width,
    height: savedWindowState.height,
    show: false, // 延迟显示，等待初始化完成
    ...opts
  }

  // 恢复窗口位置（如果之前保存过）
  if (savedWindowState.x !== undefined && savedWindowState.y !== undefined) {
    windowOptions.x = savedWindowState.x
    windowOptions.y = savedWindowState.y
  }

  const electronWindow = new BaseWindow(windowOptions)

  // 恢复浏览器最大化状态
  if (savedWindowState.isMaximized) {
    electronWindow.maximize()
  }

  /**
   * 保存窗口状态
   *
   * @private
   * @description 使用防抖优化，避免频繁保存状态
   */
  const saveWindowState = debounce(() => {
    try {
      if (electronWindow.isDestroyed()) return

      if (electronWindow.isMaximized()) {
        store.set('isMaximized', true)
      } else {
        const windowBounds = electronWindow.getBounds()
        store.set({
          isMaximized: false,
          width: Math.round(windowBounds.width),
          height: Math.round(windowBounds.height),
          x: Math.round(windowBounds.x),
          y: Math.round(windowBounds.y)
        })
      }
    } catch (error) {
      console.error('保存窗口状态时发生错误:', error)
    }
  }, 200)

  // 监听窗口移动事件，实时保存位置
  electronWindow.on('move', saveWindowState)

  // 监听窗口大小调整事件，实时保存尺寸
  electronWindow.on('resize', saveWindowState)

  // 监听窗口最大化事件，保存最大化状态
  electronWindow.on('maximize', saveWindowState)

  // 监听窗口取消最大化事件，保存正常状态
  electronWindow.on('unmaximize', saveWindowState)

  return electronWindow
}
